import { ref } from "vue";
import { ElMessage } from "element-plus";
import {
  getUserFollowersApi,
  getUserFollowingApi,
  getUserLikedArticlesApi,
  getUserCollectedArticlesApi,
  type PageParams
} from "@/api/user-profile";
import type {
  LikedArticle,
  CollectedArticle,
  FollowingUser,
  FollowerUser,
  PageResponse
} from "@/types/user-interactions";

/**
 * 用户粉丝数据管理
 */
export function useUserFollowers(userId: number) {
  const loading = ref(false);
  const data = ref<PageResponse<FollowerUser> | null>(null);
  const currentPage = ref(1);
  const pageSize = ref(10);

  const loadData = async (page?: number, size?: number) => {
    if (!userId) return;

    try {
      loading.value = true;
      const params: PageParams = {
        page: page || currentPage.value,
        size: size || pageSize.value
      };

      console.log(
        `📡 加载用户粉丝列表 - 用户ID: ${userId}, 页码: ${params.page}`
      );
      const response = await getUserFollowersApi(userId, params);

      if (response && "data" in response && response.code === 200) {
        data.value = response.data;
        currentPage.value = params.page!;
        pageSize.value = params.size!;
      } else if (response && "records" in response) {
        data.value = response as PageResponse<FollowerUser>;
        currentPage.value = params.page!;
        pageSize.value = params.size!;
      }
    } catch (error) {
      console.error("加载粉丝列表失败:", error);
      ElMessage.error("加载粉丝列表失败");
    } finally {
      loading.value = false;
    }
  };

  const handlePageChange = (page: number) => {
    loadData(page, pageSize.value);
  };

  const handleSizeChange = (size: number) => {
    pageSize.value = size;
    loadData(1, size);
  };

  return {
    loading,
    data,
    currentPage,
    pageSize,
    loadData,
    handlePageChange,
    handleSizeChange
  };
}

/**
 * 用户关注数据管理
 */
export function useUserFollowing(userId: number) {
  const loading = ref(false);
  const data = ref<PageResponse<FollowingUser> | null>(null);
  const currentPage = ref(1);
  const pageSize = ref(10);

  const loadData = async (page?: number, size?: number) => {
    if (!userId) return;

    try {
      loading.value = true;
      const params: PageParams = {
        page: page || currentPage.value,
        size: size || pageSize.value
      };

      console.log(
        `📡 加载用户关注列表 - 用户ID: ${userId}, 页码: ${params.page}`
      );
      const response = await getUserFollowingApi(userId, params);

      if (response && "data" in response && response.code === 200) {
        data.value = response.data;
        currentPage.value = params.page!;
        pageSize.value = params.size!;
      } else if (response && "records" in response) {
        data.value = response as PageResponse<FollowingUser>;
        currentPage.value = params.page!;
        pageSize.value = params.size!;
      }
    } catch (error) {
      console.error("加载关注列表失败:", error);
      ElMessage.error("加载关注列表失败");
    } finally {
      loading.value = false;
    }
  };

  const handlePageChange = (page: number) => {
    loadData(page, pageSize.value);
  };

  const handleSizeChange = (size: number) => {
    pageSize.value = size;
    loadData(1, size);
  };

  // 从列表中移除某个用户（取消关注后）
  const removeUser = (targetUserId: number) => {
    if (data.value && data.value.records) {
      const index = data.value.records.findIndex(
        user => user.userId === targetUserId
      );
      if (index > -1) {
        data.value.records.splice(index, 1);
        data.value.total--;
      }
    }
  };

  return {
    loading,
    data,
    currentPage,
    pageSize,
    loadData,
    handlePageChange,
    handleSizeChange,
    removeUser
  };
}

/**
 * 用户点赞文章数据管理
 */
export function useUserLikedArticles(userId: number) {
  const loading = ref(false);
  const data = ref<PageResponse<LikedArticle> | null>(null);
  const currentPage = ref(1);
  const pageSize = ref(10);

  const loadData = async (page?: number, size?: number) => {
    if (!userId) return;

    try {
      loading.value = true;
      const params: PageParams = {
        page: page || currentPage.value,
        size: size || pageSize.value
      };

      console.log(
        `📡 加载用户点赞文章列表 - 用户ID: ${userId}, 页码: ${params.page}`
      );
      const response = await getUserLikedArticlesApi(userId, params);

      if (response && "data" in response && response.code === 200) {
        data.value = response.data;
        currentPage.value = params.page!;
        pageSize.value = params.size!;
      } else if (response && "records" in response) {
        data.value = response as PageResponse<LikedArticle>;
        currentPage.value = params.page!;
        pageSize.value = params.size!;
      }
    } catch (error) {
      console.error("加载点赞文章列表失败:", error);
      ElMessage.error("加载点赞文章列表失败");
    } finally {
      loading.value = false;
    }
  };

  const handlePageChange = (page: number) => {
    loadData(page, pageSize.value);
  };

  const handleSizeChange = (size: number) => {
    pageSize.value = size;
    loadData(1, size);
  };

  // 从列表中移除某篇文章（取消点赞后）
  const removeArticle = (articleId: number) => {
    if (data.value && data.value.records) {
      const index = data.value.records.findIndex(
        article => article.articleId === articleId
      );
      if (index > -1) {
        data.value.records.splice(index, 1);
        data.value.total--;
      }
    }
  };

  return {
    loading,
    data,
    currentPage,
    pageSize,
    loadData,
    handlePageChange,
    handleSizeChange,
    removeArticle
  };
}

/**
 * 用户收藏文章数据管理
 */
export function useUserCollectedArticles(userId: number) {
  const loading = ref(false);
  const data = ref<PageResponse<CollectedArticle> | null>(null);
  const currentPage = ref(1);
  const pageSize = ref(10);

  const loadData = async (page?: number, size?: number) => {
    if (!userId) return;

    try {
      loading.value = true;
      const params: PageParams = {
        page: page || currentPage.value,
        size: size || pageSize.value
      };

      console.log(
        `📡 加载用户收藏文章列表 - 用户ID: ${userId}, 页码: ${params.page}`
      );
      const response = await getUserCollectedArticlesApi(userId, params);

      if (response && "data" in response && response.code === 200) {
        data.value = response.data;
        currentPage.value = params.page!;
        pageSize.value = params.size!;
      } else if (response && "records" in response) {
        data.value = response as PageResponse<CollectedArticle>;
        currentPage.value = params.page!;
        pageSize.value = params.size!;
      }
    } catch (error) {
      console.error("加载收藏文章列表失败:", error);
      ElMessage.error("加载收藏文章列表失败");
    } finally {
      loading.value = false;
    }
  };

  const handlePageChange = (page: number) => {
    loadData(page, pageSize.value);
  };

  const handleSizeChange = (size: number) => {
    pageSize.value = size;
    loadData(1, size);
  };

  // 从列表中移除某篇文章（取消收藏后）
  const removeArticle = (articleId: number) => {
    if (data.value && data.value.records) {
      const index = data.value.records.findIndex(
        article => article.articleId === articleId
      );
      if (index > -1) {
        data.value.records.splice(index, 1);
        data.value.total--;
      }
    }
  };

  return {
    loading,
    data,
    currentPage,
    pageSize,
    loadData,
    handlePageChange,
    handleSizeChange,
    removeArticle
  };
}
